﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TianShu.Untils.Encrypt;
using Volo.Abp.Modularity;
using Volo.Abp.DependencyInjection;
using System.Security.Cryptography;

namespace SPCS.Common.Helper
{
    public class RsaEncrypt : IRsaEncrypt, ISingletonDependency
    {

        /// <summary>
        /// Create a pair of keys 
        /// </summary>
        /// <param name="strength"></param>
        /// <returns></returns>
        public static (string, string) CreateKey(int strength = 2048)
        {
            RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), strength));
            AsymmetricCipherKeyPair keys = rsaKeyPairGenerator.GenerateKeyPair();
            TextWriter privateTextWriter = new StringWriter();
            PemWriter pemWriter = new PemWriter(privateTextWriter);
            pemWriter.WriteObject(keys.Private);
            pemWriter.Writer.Flush();
            StringWriter stringWriter = new StringWriter();
            PemWriter pemWriter2 = new PemWriter(stringWriter);
            pemWriter2.WriteObject(keys.Public);
            pemWriter2.Writer.Flush();
            return (stringWriter.ToString(), privateTextWriter.ToString());
        }
        public string Decrypt(string decryptstring)
        {
            return Decrypt(PrivateKey, decryptstring);
        }

        /// <summary>
        /// RSA decrypt method
        /// </summary>
        /// <param name="privateKey">SA algorithm private key</param>
        /// <param name="decryptstring">A string that need to be decrypted</param>
        /// <returns></returns>
        public string Decrypt(string privateKey, string decryptstring)
        {
            using (TextReader reader = new StringReader(privateKey))
            {
                dynamic key = new PemReader(reader).ReadObject();
                Pkcs1Encoding rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
                if (key is AsymmetricKeyParameter)
                {
                    key = (AsymmetricKeyParameter)key;
                }
                else if (key is AsymmetricCipherKeyPair)
                {
                    key = ((AsymmetricCipherKeyPair)key).Private;
                }
                rsaDecrypt.Init(false, key);
                byte[] entData2 = Convert.FromBase64String(decryptstring);
                entData2 = rsaDecrypt.ProcessBlock(entData2, 0, entData2.Length);
                return Encoding.UTF8.GetString(entData2);
            }
        }
        /// <summary>
        /// this is RSA encrypt method.
        /// </summary>
        /// <param name="publicKey">RSA algorithm public key</param>
        /// <param name="encryptstring">A string that needs to be encrypted</param>
        /// <returns></returns>
        public string Encrypt(string publicKey, string encryptstring)
        {
            using (TextReader reader = new StringReader(publicKey))
            {
                AsymmetricKeyParameter key = new PemReader(reader).ReadObject() as AsymmetricKeyParameter;
                Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding(new RsaEngine());
                pkcs1Encoding.Init(forEncryption: true, key);
                byte[] entData2 = Encoding.UTF8.GetBytes(encryptstring);
                entData2 = pkcs1Encoding.ProcessBlock(entData2, 0, entData2.Length);
                return Convert.ToBase64String(entData2);
            }
        }

        /// <summary>
        /// this is RSA encrypt method.
        /// </summary>
        /// <param name="publicKey">RSA algorithm public key</param>
        /// <param name="encryptstring">A string that needs to be encrypted</param>
        /// <returns></returns>
        public string Encrypt(string encryptstring)
        {
            return Encrypt(PublicKey, encryptstring);
        }

        public string GetPublicKey()
        {
            return PublicKey;
        }

        public static string PrivateKey { get; set; }
        public static string PublicKey { get; set; }

        static RsaEncrypt()
        {
            var key = CreateKey(2048);
            PublicKey = key.Item1;
            PrivateKey = key.Item2;
        }


        /// <summary>
        /// 最大加密长度
        /// </summary>
        private const int MAX_ENCRYPT_BLOCK = 245;

        /// <summary>
        /// 最大解密长度
        /// </summary>
        private const int MAX_DECRYPT_BLOCK = 256;

        /// <summary>
        /// 用私钥给数据进行RSA加密
        /// </summary>
        /// <param name="xmlPrivateKey"></param>
        /// <param name="strEncryptString"></param>
        /// <returns></returns>
        public string PrivateKeyEncrypt(string xmlPrivateKey, string strEncryptString)
        {
            //加载私钥
            RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();
            privateRsa.FromXmlString(xmlPrivateKey);

            //转换密钥
            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式

            c.Init(true, keyPair.Private);//第一个参数为true表示加密，为false表示解密；第二个参数表示密钥
            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);//获取字节

            byte[] cache;
            int time = 0;//次数
            int inputLen = dataToEncrypt.Length;
            int offSet = 0;

            MemoryStream outStream = new MemoryStream();
            while (inputLen - offSet > 0)
            {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
                {
                    cache = c.DoFinal(dataToEncrypt, offSet, MAX_ENCRYPT_BLOCK);
                }
                else
                {
                    cache = c.DoFinal(dataToEncrypt, offSet, inputLen - offSet);
                }
                //写入
                outStream.Write(cache, 0, cache.Length);

                time++;
                offSet = time * MAX_ENCRYPT_BLOCK;
            }

            byte[] resData = outStream.ToArray();

            string strBase64 = Convert.ToBase64String(resData);
            outStream.Close();
            return strBase64;
        }

        /// <summary>
        /// 用公钥给数据进行RSA解密 
        /// </summary>
        /// <param name="xmlPublicKey"> 公钥(XML格式字符串) </param>
        /// <param name="strDecryptString"> 要解密数据 </param>
        /// <returns> 解密后的数据 </returns>
        public string PublicKeyDecrypt(string xmlPublicKey, string strDecryptString)
        {
            //加载公钥
            RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();
            publicRsa.FromXmlString(xmlPublicKey);
            RSAParameters rp = publicRsa.ExportParameters(false);

            //转换密钥
            AsymmetricKeyParameter pbk = DotNetUtilities.GetRsaPublicKey(rp);

            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
            //第一个参数为true表示加密，为false表示解密；第二个参数表示密钥
            c.Init(false, pbk);

            byte[] DataToDecrypt = Convert.FromBase64String(strDecryptString);

            byte[] cache;
            int time = 0;//次数
            int inputLen = DataToDecrypt.Length;
            int offSet = 0;
            MemoryStream outStream = new MemoryStream();
            while (inputLen - offSet > 0)
            {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK)
                {
                    cache = c.DoFinal(DataToDecrypt, offSet, MAX_DECRYPT_BLOCK);
                }
                else
                {
                    cache = c.DoFinal(DataToDecrypt, offSet, inputLen - offSet);
                }
                //写入
                outStream.Write(cache, 0, cache.Length);

                time++;
                offSet = time * MAX_DECRYPT_BLOCK;
            }
            byte[] resData = outStream.ToArray();

            string strDec = Encoding.UTF8.GetString(resData);
            return strDec;
        }

    }


}
